const { ipcMain, BrowserWindow } = require('electron')
const { URL } = require('url')

const getSource = (url) => {
  return new Promise((resolve, reject) => {
    let win = new BrowserWindow({
      width: 500,
      height: 500,
      show: false,
      webPreferences: {
        offscreen: true
      }
    })
    win.loadURL(url)

    win.webContents.on('did-finish-load', async () => {
      let title = win.getTitle()

      try {
        let image = await win.webContents.capturePage()
        let screenshot = image.toDataURL()
        let href = (new URL(url)).href
        
        resolve({
          title,
          screenshot,
          url,
          href
        })
      } catch (error) {
        reject(error)
      }
    })
  })
}

ipcMain.handle('on-url-event', async (event, ...args) => {
  const result = await getSource(...args)
  return result
})